var http = require('http'),
    fs = require('fs'),
    util = require('util');

http.createServer(function (request, response) {
	var options = {
        port : 80,
        host : request.headers['host'],
        method : request.method,
        headers : request.headers,
        path : request.url
    }
    var client = http.request(options, function(res) {
    	log('http.request STATUS: ' + res.statusCode);
    	response.writeHead(res.statusCode, res.headers);
    	res.on('data', function (chunk) {
			response.write(chunk, 'binary');
		});
		res.on('end', function() {
			saveLog(request.method, request.url);
            response.end();
		});
		res.on('error', function(e) {
			log('problem with request: ' + e.message);
            response.writeHeader(404);
            response.end();
            client.destroy();
		});
    });
    client.on('error', function(){
        response.writeHeader(404);
        response.end();
        client.destroy();
    });
    request.on('data', function (chunk) {
        client.write(chunk, 'binary');
    });
    request.on('end', function () {
        client.end();
    });
    request.on('error', function () {
        client.destroy();
    });
    response.on('error',function(){
        log('[WEB] `%s` zlib err', url);
        response.writeHeader(404);
        response.end();
    });

}).listen(8088, '0.0.0.0', function(){
     console.log('proxy listen 8088.');
});

function saveLog(method, url) {
    fs.appendFileSync('./logs/proxy-new.log', util.format('[%s]\n%s %s\n\n', getFormatedTime(), method, url));
}
function log(msg,value){
    fs.appendFileSync('./logs/connection-new.log', util.format('[%s] - %s<%s>\n', getFormatedTime(), msg,value));
}
function getFormatedTime() {
    var dt = new Date();
    return dt.getFullYear() + '-' + formatNum(dt.getMonth() + 1, 2) + '-' + formatNum(dt.getDate(), 2) + ' ' + formatNum(dt.getHours(), 2) + ':' + formatNum(dt.getMinutes(), 2) + ':' + formatNum(dt.getSeconds(), 2) + '.' + formatNum(dt.getMilliseconds(), 3);
}

function formatNum(num, len) {
    return ('000' + num).slice(-len);
}    